<template>
  <div class="list">
    <van-skeleton avatar :row="2" :loading="skeLoading" row-width="100%" avatar-shape="square" :avatar-size="50"
      v-for="item in 3" />

    <van-swipe class="my-swipe" indicator-color="white" :show-indicators="false" :loop="false">
      <van-swipe-item class="item" v-for="item, index in songArr" :key="index">

        <li v-for="info in item" :key="info.id" @click="playSong(info.id)">

          <div class="music-pic">
            <van-image :src="info.picUrl" />
          </div>
          <div class="muisc-info van-ellipsis">
            <p class=" van-ellipsis">
              {{ info.name }}
              <span class="font-fu">- {{ info.song.artists[0].name }}</span>
            </p>
            <span class="info font-fu ">{{ info.song.alias[0] }}</span>
          </div>
          <div class="play">
            <van-icon name="play-circle-o" size="28" />
          </div>
        </li>
      </van-swipe-item>
    </van-swipe>
  </div>
</template>

<script setup>
import { reactive, toRefs, ref, onMounted } from 'vue'
import { getNewSong } from '@/request/api/musicApi'
import { storeToRefs } from 'pinia'
import { PlayStore } from '@/store/playlist'

const playStore = PlayStore();

let { playList, playListIndex, updateList } = storeToRefs(playStore);
onMounted(() => {
  initData();
})
let skeLoading = ref(true);
let songList = [];
let songArr = ref([]);
const initData = async () => {
  getNewSongs()
}

// 获取最新推荐歌曲
const getNewSongs = async () => {
  await getNewSong({ limit: 12 }).then((data) => {
    songList = data.result;
    // 三首歌为一组重新遍历
    for (let i = 0; i < songList.length; i += 3) {
      songArr.value.push(songList.slice(i, i + 3));
    }
    skeLoading.value = false;
  })
}

// 播放  加到Pinia
const playSong = (id) => {
  let songlistArr = []
  
  songList.forEach(item => {  // 格式化成pinia需要的
    let data = {
      al: item.song.album,
      ar: item.song.artists,
      dt: item.song.duration,
      id: item.id,  //音乐ID
      name: item.name
    }
    songlistArr.push(data)
  });

  if (id) {
    // 点击单曲播放 根据ID获取下标
    let songindex = songList.findIndex(item => item.id == id);
    playStore.updateList(songlistArr, songindex)
  } else {
    // 播放全部
    playStore.updateList(songlistArr)
  }
}


// 暴露
defineExpose({
  playSong
})
</script>
  
<style lang='less' scoped>
.van-skeleton {
  margin-bottom: 20px;
}

.van-swipe-item {
  width: 100%;

  li {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    margin: 20px 0;
    padding: 0 20px;
    box-sizing: border-box;
  }

  .music-pic {
    width: 100px;
    text-align: center;
  }

  .muisc-info {
    flex: 1;
    margin: 0 20px;

    p {
      font-size: 35px;

      span {
        font-size: 20px;
      }
    }

    .info {
      font-size: 28px;
    }
  }
}
</style>